<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/11/29
 * Time: 11:30
 */

namespace app\api\controller;


use think\Db;

class Inwarehouse extends Base
{
    /**
     * 单条入库
     * in_num  编号
     * in_name  名称
     * house_type_id  房屋类型ID
     * spec_type_id  规格类型ID
     * warehouse_id  仓库
     * in_address  地址
     * in_abstract  摘要
     * district  地区
     * user_id  当前登录者ID
     * in_img  缩略图
     * in_detail_address  详细地址
     * @return \think\response\Json
     */
    public function insertOne(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
        }
        $data = [
            'in_num' => $params['in_num'],//编号
            'in_name' => $params['in_name'],//名称
            'house_type_id' => $params['house_type_id'],//房屋类型ID
            'spec_type_id' => $params['spec_type_id'],//规格类型ID
            'warehouse_id' => $params['warehouse_id'],//仓库
            'in_address' => $params['in_address'],//地址
            'in_abstract' => $params['in_abstract'],//摘要
//            'district' => $params['district'],//地区
            'in_user_id' => $params['user_id'],//入库者ID
            'in_img' => $params['in_img'],//缩略图
            'in_status' => 1,//状态  1 审核中  2 审核通过  3 审核失败
            'create_time' => date('Y-m-d H:i:s'),//入库时间
            'in_detail_address' => $params['in_detail_address'],//详细地址
        ];
        $res = Db::table('up_in_warehouse')->insert($data);
        if($res){
            return json(['status' => 200, 'msg' => '添加成功']);
        }else{
            return json(['status' => 0, 'msg' => '添加失败']);
        }
    }

    /**
     * 批量添加
     * list   二维数组
     * in_num  编号
     * in_name  名称
     * house_type_id  房屋类型ID
     * spec_type_id  规格类型ID
     * warehouse_id  仓库
     * in_address  地址
     * in_abstract  摘要
     * district  地区
     * user_id  当前登录者ID
     * in_img  缩略图
     * in_detail_address  详细地址
     * @return \think\response\Json
     */
    public function insertBatch()
    {
        $params = input('param.');
        $list = input('param.list/a');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if ($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
//        $list = [
//            [
//                'in_num' => $params['in_num'],//编号
//                'in_name' => $params['in_name'],//名称
//                'house_type_id' => $params['house_type_id'],//房屋类型ID
//                'spec_type_id' => $params['spec_type_id'],//规格类型ID
//                'warehouse_id' => $params['warehouse_id'],//仓库
//                'in_address' => $params['in_address'],//地址
//                'in_abstract' => $params['in_abstract'],//摘要
//                'district' => $params['district'],//地区
//                'in_user_id' => $params['user_id'],//入库者ID
//                'in_img' => $params['in_img'],//缩略图
//            ],
//            [
//                'in_num' => $params['in_num'],//编号
//                'in_name' => $params['in_name'],//名称
//                'house_type_id' => $params['house_type_id'],//房屋类型ID
//                'spec_type_id' => $params['spec_type_id'],//规格类型ID
//                'warehouse_id' => $params['warehouse_id'],//仓库
//                'in_address' => $params['in_address'],//地址
//                'in_abstract' => $params['in_abstract'],//摘要
//                'district' => $params['district'],//地区
//                'in_user_id' => $params['user_id'],//入库者ID
//                'in_img' => $params['in_img'],//缩略图
//            ]
//        ];
        Db::startTrans();
        try {
            $str = '';
            foreach ($list as $key => &$va) {
                //1、判断重复，赋值
                if ($va['in_num'] == $str) {
                    Db::rollback();
                    return json(['status' => 0, 'msg' => '此编号重复：' . $va['in_num'], 'data' => []]);
                }
                $str = $va['in_num'];
                //2、存在不存在
                $isIn = Db::table('up_in_warehouse')
                    ->where('in_num', $va['in_num'])
                    ->order('create_time desc')
                    ->field('in_status')
                    ->find();
                if ($isIn) {
                    if ($isIn['in_status'] != 3) {
                        Db::rollback();
                        return json(['status' => 0, 'msg' => '此编号已存在：' . $va['in_num'], 'data' => []]);
                    }
                }
                $data = [
                    'in_num' => $va['in_num'],//编号
                    'in_name' => $va['in_name'],//名称
                    'house_type_id' => $va['house_type_id'],//房屋类型ID
                    'spec_type_id' => $va['spec_type_id'],//规格类型ID
                    'warehouse_id' => $va['warehouse_id'],//仓库
                    'in_address' => $va['in_address'],//地址
                    'in_abstract' => $va['in_abstract'],//摘要
                    'in_user_id' => $params['user_id'],//入库者ID
                    'in_img' => $va['in_img'],//缩略图
                    'in_status' => 1,//状态  1 审核中  2 审核通过  3 审核失败
                    'create_time' => date('Y-m-d H:i:s'),//入库时间
                    'in_detail_address' => $va['in_detail_address'],//详细地址
                ];
                Db::table('up_in_warehouse')->insert($data);
            }
            Db::commit();
            return json(['status' => 200, 'msg' => '成功', 'data' => []]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '入库失败，请重试']);
        }
    }

    /**
     * 获取仓库列表
     * @return \think\response\Json
     */
    public function warehouse(){
        $warehouseList = Db::table('up_warehouse')
            ->field('house_id, warehouse_name')
            ->select();
        return json(['status' => 200, 'msg' => '', 'data' => $warehouseList]);
    }

    /**
     * 获取房屋类型列表
     * @return \think\response\Json
     */
    public function houseType(){
        $houseTypeList = Db::table('up_house_type')
            ->field('house_type_id, house_type')
            ->select();
        return json(['status' => 200, 'msg' => '', 'data' => $houseTypeList]);
    }

    /**
     * 获取房屋类型列表
     * @return \think\response\Json
     */
    public function specType(){
        $specTypeList = Db::table('up_spec_type')
            ->field('spec_type_id, spec_type')
            ->select();
        return json(['status' => 200, 'msg' => '', 'data' => $specTypeList]);
    }

    /**
     * 生成编号
     * spec_type_id  规格类型ID
     * in_type  入库的方式  1 手动录入  2 扫码录入时，修改规格类型
     * in_num  后台生成的编号  当in_type为2时，如果用户需要修改编号，这传此值
     * @return \think\response\Json
     */
    public function createNum(){
        $spec_type_id = input('param.spec_type_id');//规格ID
        $old_num = input('param.in_num')?input('param.in_num'):'';//后台生成的编号
        $in_type = input('param.in_type');//入库方式
        //获取编号前缀
        $spec_code = Db::table('up_spec_type')
            ->where('spec_type_id', $spec_type_id)
            ->value('spec_code');
        if($in_type == 1){//手动录入
            //入库表最大ID
            $inMaxId = Db::table('up_in_warehouse')->max('in_id');
            $newInQrcodeId = $inMaxId + 1;//最大ID加1
            $leng1 = strlen($newInQrcodeId);
            $zero1 = '';
            if($leng1 < 5){
                for($i = $leng1; $i < 5; $i++){
                    $zero1 .= '0';
                }
            }
            $in_num = $spec_code . '-' . $zero1 . $newInQrcodeId . '00000';
        }else{//扫码后，需要修改规格类型
            $old_num = explode('-', $old_num);
            //更换前缀
            $old_num[0] = $spec_code;
            $in_num = implode('-', $old_num);
        }
        return json(['status' => 200, 'msg' => '', 'data' => $in_num]);
    }

    /**
     * 入库排行
     * @return \think\response\Json
     */
    public function inWarehouseList(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
        }
        //我所属的仓库
        $warehouse_id = Db::table('up_u_user')->where('user_id', $params['user_id'])->value('warehouse_id');
        //获取列表
        $lists = Db::table('up_in_warehouse')
            ->field('in_id, in_img, in_name, check_time, in_abstract')
            ->where('warehouse_id', $warehouse_id)
            ->where('in_status', 2)
            ->order('check_time desc')
            ->limit(10)
            ->select();

        if($lists){
            foreach($lists as $key => &$list){
                //修改时间格式
                $list['check_time'] = date('Y-m-d H:i', strtotime($list['check_time']));
                //组装图片
                if(empty($list['in_img'])){
                    $list['in_img'] = null;
                }else{
                    $list['in_img'] = http_type() . "/" . $list['in_img'];
                }
            }
        }
        return json(['status' => 200, 'msg' => '', 'data' => $lists]);
    }

    /**
     * 用户信息
     * @return \think\response\Json
     */
    public function userInfo(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
        }
        //用户信息
        $userInfo = Db::table('up_u_user')
            ->where('user_id', $params['user_id'])
            ->field('user_username, user_image')
            ->find();
        $userInfo['user_image'] = http_type() . $userInfo['user_image'];
        return json(['status' => 200, 'msg' => '', 'data' => $userInfo]);
    }

    /**
     * 待审核物件列表
     * @return \think\response\Json
     */
    public function checkList(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
        }
        //获取所在仓库
        $warehouse = Db::table('up_u_user')
            ->where('user_id', $params['user_id'])
            ->value('warehouse_id');
        //获取列表
        $lists = Db::table('up_in_warehouse')
            ->alias('uiw')
            ->join('up_u_user uuu', 'uuu.user_id = uiw.in_user_id', 'left')
            ->join('up_warehouse uw', 'uw.house_id = uiw.warehouse_id', 'left')
            ->field('in_id, in_name, in_num, user_image, user_username, warehouse_name')
            ->where('uiw.warehouse_id', $warehouse)
            ->where('in_status', 1)
            ->select();
        //图片处理
        if($lists){
            foreach($lists as $key => &$list){
                if(empty($list['user_image'])){
                    $list['user_image'] = null;
                }else{
                    $list['user_image'] = http_type() . "/" . $list['user_image'];
                }
            }
        }
        return json(['status' => 200, 'msg' => '', 'data' => $lists]);
    }

    /**
     * 待审核物件详情
     * @return \think\response\Json
     */
    public function checkDetail(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
        }
        $detail = Db::table('up_in_warehouse')
            ->alias('uiw')
            ->join('up_u_user uuu', 'uuu.user_id = uiw.in_user_id', 'left')
            ->join('up_warehouse uw', 'uw.house_id = uiw.warehouse_id', 'left')
            ->join('up_spec_type ust', 'ust.spec_type_id = uiw.spec_type_id', 'left')
            ->join('up_house_type uht', 'uht.house_type_id = uiw.house_type_id', 'left')
            ->field('user_image, user_username, in_num, in_name, in_address, in_abstract, warehouse_name,
            spec_type, house_type')
            ->where('in_id', $params['in_id'])
            ->find();
        //图片
        if($detail){
            if(empty($detail['user_image'])){
                $detail['user_image'] = null;
            }else{
                $detail['user_image'] = http_type() . "/" . $detail['user_image'];
            }
        }
        return json(['status' => 200, 'msg' => '', 'data' => $detail]);
    }

    /**
     * 审核
     * status  审核状态  2 通过  3 未通过
     * in_id  物件ID
     * @return \think\response\Json
     */
    public function checkBuild(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
        }
        $update = [
            'in_status' => $params['status'],//审核状态  2 通过  3 未通过
            'check_user_id' => $params['user_id'],//审核者
            'check_time' => date('Y-m-d H:i:s'),//审核时间
        ];

        $res = Db::table('up_in_warehouse')->where('in_id', $params['in_id'])->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '审核成功', 'data' => []]);
        }else{
            return json(['status' => 0, 'msg' => '操作数据库失败', 'data' => []]);
        }
    }

    /**
     * 读取扫描二维码信息
     * in_num  读取到的编号
     * @return \think\response\Json
     */
    public function readQrcodeInfo(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
        }
        $isIn = Db::table('up_in_warehouse')
            ->where('in_num', $params['in_num'])
            ->order('create_time desc')
            ->find();
        //是否重复录入
//        if($isIn){
//            if($isIn['in_status'] != 3){
//                return json(['status' => 0, 'msg' => '该物件已录入', 'data' => []]);
//            }
//        }
        //根据扫码获取的编号，查找相关信息
        $info = Db::table('up_code_warehouse')
            ->alias('ucw')
            ->join('up_house_type uht', 'uht.house_type_id = ucw.house_type_id', 'left')
            ->join('up_spec_type ust', 'ust.spec_type_id = ucw.spec_type_id', 'left')
            ->join('up_warehouse uw', 'uw.house_id = ucw.warehouse_id', 'left')
            ->field(['code_id', 'in_num', 'house_type', 'spec_type', 'warehouse_name',
                'in_name', 'in_img', 'in_abstract', 'is_del', 'in_address', 'ucw.house_type_id',
                'ucw.spec_type_id', 'ucw.warehouse_id'])
            ->where('in_num', $params['in_num'])
            ->find();
        if(empty($info) || $info['is_del'] == 2){
            return json(['status' => 0, 'msg' => '数据不存在', 'data' => []]);
        }
        //该物件状态
        if($isIn){
            $info['in_status'] = $isIn['in_status'];//已入库  1 审核中  2 审核通过  3 审核失败
        }else{
            $info['in_status'] = -1;//未入库
        }
        return json(['status' => 200, 'msg' => '', 'data' => $info]);
    }

    /**
     * 今日入库/今日审核
     * @return \think\response\Json
     */
    public function todayInWarehouse(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
        }
        $startTime = date('Y-m-d 00:00:00');//今日开始时间
        $endTime = date('Y-m-d 23:59:59');//今日结束时间
        //用户角色  1 入库  2 库管
        $user_role = Db::table('up_u_user')->where('user_id', $params['user_id'])->value('user_role');
        if($user_role == 1){
            $where['in_user_id'] = $params['user_id'];
            $where['in_status'] = 2;//已审核通过
        }else{
            $where['check_user_id'] = $params['user_id'];
            $where['in_status'] = ['neq', 1];//通过或者拒绝的
        }
        $where['check_time'] = ['between', [$startTime, $endTime]];//今日
        $page = input('page')?input('page'):1;
        $todayInWarehouse = Db::table('up_in_warehouse')
            ->alias('uiw')
            ->join('up_u_user uuu', 'uuu.user_id = uiw.in_user_id', 'left')
            ->join('up_warehouse uw', 'uw.house_id = uiw.warehouse_id', 'left')
            ->field(['in_id', 'user_username', "concat('".http_type()."',user_image)"=>'user_image',
                'in_name', 'in_num', 'warehouse_name'])
            ->where($where)
            ->page($page, 10)
            ->order('check_time desc')
            ->select();
        return json(['status' => 200, 'msg' => '', 'data' => $todayInWarehouse]);
    }

    /**
     * 我经手的
     * @return \think\response\Json
     */
    public function mine(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
        }
        //用户角色  1 入库  2 库管
        $user_role = Db::table('up_u_user')->where('user_id', $params['user_id'])->value('user_role');
        if($user_role == 1){
            $where['in_user_id'] = $params['user_id'];
        }else{
            $where['check_user_id'] = $params['user_id'];
        }
        $page = input('page')?input('page'):1;
        $myInWarehouse = Db::table('up_in_warehouse')
            ->alias('uiw')
            ->join('up_u_user uuu', 'uuu.user_id = uiw.in_user_id', 'left')
            ->join('up_warehouse uw', 'uw.house_id = uiw.warehouse_id', 'left')
            ->field(['in_id', 'user_username', "concat('".http_type()."',user_image)"=>'user_image',
                'in_name', 'in_num', 'warehouse_name'])
            ->where($where)
            ->page($page, 10)
            ->order('in_id desc')
            ->select();
        return json(['status' => 200, 'msg' => '', 'data' => $myInWarehouse]);
    }
}